const util = require("../../utils/util.js");
const app = getApp();
Component({
  properties: {
    // 这里定义了 headerText 属性，属性值可以在组件使用时指定
    type: Number, //type为0:有素材的弹窗 1:没有素材
    path: String,
    info: Object
  },
  data: {
    // 组件内部数据
    postersModal: false,
    posterInfo: {
      avater: 'https://images.unsplash.com/photo-1551334787-21e6bd3ab135'
    },
    qrCode: "http://i4.hexun.com/2018-07-05/193365388.jpg", //二维码图片
    showMaterialModal: false,
    maskShowModel: false,
    minPrice: 88,
    maxPrice: 98,
    imagePath: ''
  },
  ready: function() {
    console.log(this.properties.type)
  },
  methods: {
    // 自定义方法
    posters: function() {
      console.log('点击了海报')
      this.setData({
        postersModal: true
      })
      var that = this;
      var path = that.data.path;
      if (path == 'goodsDetail') {
        that.createGoodsShareImg()
      } else if (path == 'luckyDetail') {
        console.log('luckyDetail')
        that.createLuckyShareImg()
      } else if (path == 'foundDetail') {
        console.log('foundDetail')
        that.createFoundShareImg()
      } else if (path == 'pingDetail') {
        that.createPingShareImg()
      }
    },
    //商品详情页的分享好友海报
    createGoodsShareImg() {
      var that = this;
      console.log(that.data.model)
      let drawCount = 1;
      let drawAll = 8;
      that.setData({
        imagePath: ""
      });
      var context = wx.createCanvasContext('mycanvas', that);
      context.setFillStyle("#ffffff")
      context.fillRect(0, 0, 243, 381);
      wx.downloadFile({
        url: 'http://i4.hexun.com/2018-07-05/193365388.jpg',
        success: function(res) {
          context.save()
          context.beginPath()
          context.arc(25, 25, 15, 0, 2 * Math.PI)
          context.clip()
          // context.drawImage(res.tempFilePath, 140, 310, 60, 60)
          context.drawImage('../../images/logo.png', 10, 10, 30, 30);
          context.restore()
          context.draw(true)
        }
      })

      context.save();
      context.setFontSize(10);
      context.setFillStyle('#434343');
      context.font = 'normal normal 10px PingFangSC-Light';
      context.fillText("万千好物", 44, 22)
      context.fillText("从简开始", 44, 36)
      context.restore();
      app.downloadFile("https://obs.cn-north-1.myhuaweicloud.com/obs-7d37/hh_shequ/hoshii.png").then(res => {
        context.drawImage(res.tempFilePath, 134, 0, 109, 60);
        context.draw(true, () => {
          that.saveTempImage(drawCount++, drawAll);
        });
      }).catch(res => {
        app.showToast("下载图片失败")
        drawCount++;
      })
      app.downloadFile('https://obs.cn-north-1.myhuaweicloud.com/obs-7d37/hh_shequ/logo.png' + "?x-image-process=image/resize,m_pad,w_185,h_190").then(res => {
        context.save();
        that.roundRect(context, 10, 60, 223, 190, 5);
        context.setFillStyle('white')
        context.fillRect(10, 60, 223, 190)
        // context.drawImage(res.tempFilePath, 12, 75, 185, 190);
        context.drawImage('../../images/logo.png', 10, 60, 223, 190);
        context.restore();
        context.draw(true, () => {
          that.saveTempImage(drawCount++, drawAll);
        });
      }).catch(res => {
        app.showToast("下载图片失败")
        drawCount++;
      })
      context.save();
      that.fillTextEclip(context, "商品名商品名商品名商品名商品名", 10, 270, 153, 12, 18, "bold", "PingFangSC-Semibold");
      context.restore();
      context.draw(true, () => {
        that.saveTempImage(drawCount++, drawAll);
      });

      context.save();
      context.setFontSize(20);
      context.font = 'normal bold 20px PingFangSC-Semibold';
      context.setFillStyle('#E93324');
      context.fillText("￥", 10, 330);
      context.font = 'normal bold 32px PingFangSC-Semibold';
      context.setFontSize(32);
      context.fillText(that.data.minPrice, 28, 330);
      let priceWidth = 26 * (that.data.minPrice + "").length - 13
      if ((that.data.minPrice + "").indexOf(".") === -1) {
        priceWidth = priceWidth + 13
      }
      context.restore();
      context.draw(true, () => {
        that.saveTempImage(drawCount++, drawAll);
      });
      context.save();
      context.font = 'normal normal 12px PingFangSC-Regular';
      context.setFillStyle('#999');
      context.fillText("￥", 20 + priceWidth + 0, 322);
      context.fillText(that.data.maxPrice, 20 + priceWidth + 10, 322);
      let priceWidth1 = 7 * (that.data.maxPrice + "").length
      context.moveTo(20 + priceWidth + 2, 318)
      context.lineTo(20 + priceWidth + 7 + priceWidth1, 318)
      context.setStrokeStyle('#999')
      context.stroke();
      context.restore();
      context.save();
      context.draw(true, () => {
        that.saveTempImage(drawCount++, drawAll);
      });
      that.roundRect(context, 10, 345, 223, 20, 5);
      context.setFillStyle('#FBF2E8')
      context.fillRect(10, 345, 223, 36)
      context.restore();
      context.save();
      context.setFontSize(10);
      context.setFillStyle('#333333');
      context.font = 'normal 10px PingFangSC-Regular';
      context.setTextAlign('center')
      context.fillText("长按识别小程序码了解商品详情", 114, 358);

      context.restore();
      context.draw(true, () => {
        that.saveTempImage(drawCount++, drawAll);
      });
      let userId = "";
      let userBean = app.globalData.userBean;
      if (userBean && userBean.consumerId) {
        userId = userBean.consumerId
      }
      // api.getShareInfo(userId, 2, that.data.model.spuId).then(res => {
      app.downloadFile(this.data.qrCode + "?x-image-process=image/resize,m_pad,w_60,h_60").then(res => {
        console.log(res);
        context.save();
        context.beginPath()
        context.arc(203, 300, 30, 0, 2 * Math.PI) //画出圆
        context.strokeStyle = "#fff";
        context.clip();
        context.drawImage(res.tempFilePath, 173, 270, 60, 60);
        context.restore();
        context.draw(true, () => {
          that.saveTempImage(drawCount++, drawAll);
        });
      }).catch(res => {
        wx.hideLoading();
        app.showToast("下载分享二维码失败!")
        that.setData({
          showShareImage: false
        });
      })
      // }).catch(msg => {
      //   wx.hideLoading();
      //   app.showToast("获取分享二维码失败!")
      //   that.setData({
      //     showShareImage: false
      //   });
      // })
    },


    //绘制抽奖详情海报分享
    createLuckyShareImg() {
      var that = this;
      var context = wx.createCanvasContext('mycanvas', that);
      context.save()
      context.setFillStyle('#F15453');
      context.fillRect(0, 0, 209, 335),
        wx.downloadFile({
          url: 'http://i4.hexun.com/2018-07-05/193365388.jpg',
          success: function(res) {
            context.save()
            context.beginPath()
            context.arc(104, 30, 20, 0, 2 * Math.PI)
            context.clip()
            context.drawImage('../../images/logo.png', 84, 10, 40, 40);
            context.restore()
            context.draw(true)
          }
        })
      context.setFontSize(9);
      context.setFillStyle('#ffffff');
      context.fillText('快来一起免费抽奖,看看谁的手气更好!', 30, 68);
      that.roundRect(context, 10, 82, 189, 245, 10);
      context.setFillStyle('white')
      context.fillRect(10, 82, 189, 245)

      context.setFillStyle('#f2f2f2')
      context.fillRect(10, 86, 189, 100),
        context.drawImage('../../images/goods-test.png', 10, 86, 189, 100);
      context.setTextAlign('center');
      that.fillTextEclip(context, "商品名商品名商品名商品名商品名商品名商", 105, 198, 165, 11, 18, "bold", "PingFangSC-Semibold");
      context.restore();
      context.setFontSize(8);
      context.setFillStyle('#F15453');
      context.fillText('价值¥69元', 30, 236);
      context.setFillStyle('#000000');
      context.fillText('7月4日 21:00 自动开奖', 80, 236);

      wx.downloadFile({
        url: 'http://i4.hexun.com/2018-07-05/193365388.jpg',
        success: function(res) {
          context.save()
          context.beginPath()
          context.arc(104, 278, 30, 0, 2 * Math.PI)
          context.clip()
          context.drawImage(res.tempFilePath, 74, 248, 60, 60)
          context.restore()
          context.draw(true)
        }
      })
      context.setFontSize(8);
      context.setFillStyle('#666666');
      context.fillText('长按图片识别,马上参与抽奖', 55, 320);
      context.draw(true)
    },
    //绘制发现详情的分享海报
    createFoundShareImg() {
      var that = this;
      let drawCount = 1;
      let drawAll = 8;
      var context = wx.createCanvasContext('mycanvas', that);
      context.save()
      context.setFillStyle('#ffffff');
      context.fillRect(0, 0, 209, 372),
        wx.downloadFile({
          url: "https://obs.cn-north-1.myhuaweicloud.com/obs-7d37/hh_shequ/jrbg.png",
          success(res) {
            // context.drawImage(res.tempFilePath, 148, 166, 80, 20);
            context.drawImage('../../images/logo.png', 10, 10, 20, 12);
            context.draw(true, () => {
              that.saveTempImage(drawCount++, drawAll);
            });
          }
        })

      context.setFontSize(10);
      context.setFillStyle('#434343');
      context.fillText("来自", 34, 18)
      context.fillText("的分享", 118, 18)
      context.font = 'normal bold 10px PingFangSC-Semibold';
      context.fillText("简选种草菌", 58, 18)


      context.setFontSize(12);
      context.setFillStyle('#000000');
      context.fillText('网红菠萝丝袜,3双低至29元!', 10, 48);
      context.font = 'normal normal 12px PingFangSC-Regular';
      let [contentLeng, contentArray, contentRows] = that.textByteLength('简选清货10:00推荐网红菠萝丝袜', 20);
      let contentHh = 15 * 1;
      for (let m = 0; m < contentArray.length; m++) {
        context.setFontSize(10);
        context.setFillStyle('#333333');
        context.fillText(contentArray[m], 10, 78 + contentHh * m);
      }

      context.setFontSize(20);
      context.setFillStyle('#333333');
      context.font = 'normal bold 20px PingFangSC-Semibold';
      context.fillText('可以装菠萝的丝袜', 23, 128);
      context.setFontSize(12);
      context.setFillStyle('#333333');
      context.fillText('耐磨耐刮 任意裁剪', 48, 153);

      context.setFillStyle('#333333');
      context.font = 'normal normal 9px PingFangSC-Regular';
      context.fillText('ARBITRARY SCISSORS', 48, 168);

      wx.downloadFile({
        url: "https://obs.cn-north-1.myhuaweicloud.com/obs-7d37/hh_shequ/jrbg.png",
        success(res) {
          context.drawImage('../../images/logo.png', 10, 178, 189, 100);
          context.draw(true, () => {
            that.saveTempImage(drawCount++, drawAll);
          });
        }
      })

      context.setFillStyle('#333333');
      context.font = 'normal bold 10px PingFangSC-Semibold';
      context.fillText('与世界分享您的好物心得', 10, 300);
      context.font = 'normal normal 10px PingFangSC-Regular';
      context.setFontSize(9);
      context.setFillStyle('#333333');
      context.fillText('简选,自购省钱,分享赚钱', 10, 315);
      that.roundRect(context, 10, 330, 124, 15, 5);
      context.setFillStyle('#FCF1E4')
      context.fillRect(10, 330, 124, 15)
      context.setFontSize(8);
      context.setFillStyle('#333333');
      context.fillText('长按识别小程序码了解更多详情', 12, 340);
      context.restore();
      wx.downloadFile({
        url: 'http://i4.hexun.com/2018-07-05/193365388.jpg',
        success: function(res) {
          context.save()
          context.beginPath()
          context.arc(174, 320, 30, 0, 2 * Math.PI)
          context.clip()
          context.drawImage(res.tempFilePath, 144, 290, 60, 60)
          context.restore()
          context.draw(true)
        }
      })
      context.draw(true)
    },


    //拼团详情页的分享好友海报
    createPingShareImg() {
      var that = this;
      var context = wx.createCanvasContext('mycanvas', that);
      context.save()
      context.setFillStyle('#ffffff');
      context.fillRect(0, 0, 235, 376),
      context.setFillStyle('#F15453');
      context.fillRect(0, 0, 235, 296),
      that.roundRect(context, 10, 30, 215, 220, 10);
      context.setFillStyle('white')
      context.fillRect(10, 30, 215, 220)
      wx.downloadFile({
        url: 'http://i4.hexun.com/2018-07-05/193365388.jpg',
        success: function(res) {
          context.save()
          context.beginPath()
          context.arc(117, 30, 20, 0, 2 * Math.PI)
          context.clip()
          // context.drawImage(res.tempFilePath, 140, 310, 60, 60)
          context.drawImage('../../images/logo.png', 97, 10, 40, 40);
          context.restore()
          context.draw(true)
        }
      })

      context.setFontSize(10);
      context.setFillStyle('#000000');
      context.fillText('我刚刚在简选挑到了一件好东西', 50, 64);
      context.fillText('来和我一起拼团更省钱哦', 62, 80);
      context.setFillStyle('#f2f2f2')
      context.fillRect(10, 90, 215, 100),
      context.drawImage('../../images/goods-test.png', 10, 90, 107, 100);
      that.fillTextEclip(context, "商品名商品名商品名商品名商品名商品名商品名商品名商品名商品名", 127, 100, 82, 12, 18, "bold", "PingFangSC-Semibold");
      context.drawImage('../../images/ping/guonei.png', 127, 170, 10, 10);
      context.setFontSize(10);
      context.setFillStyle('#666666');
      context.fillText('国内商品', 140, 179);
      that.roundRect(context, 25, 195, 180, 30, 18);
      context.setFillStyle('#F15453')
      context.fillRect(25, 195, 180, 30)
      context.setFontSize(12);
      context.setFillStyle('#ffffff');
      context.fillText('2人拼团价 ¥9.9', 70, 215);
      context.restore();
      context.drawImage('../../images/ping/guonei.png', 67, 232, 10, 10);
      context.setFontSize(10);
      context.setFillStyle('#000000');
      context.fillText('拼团成功返', 80, 240);
      context.setFillStyle('#F15453');
      context.fillText('¥0.9', 135, 240);
      context.setFontSize(9);
      context.setFillStyle('#ffffff');
      context.fillText('简选承诺.100%正品', 75, 265);
      context.drawImage('../../images/ping/guonei.png', 12, 277, 10, 10);
      context.drawImage('../../images/ping/guonei.png', 77, 277, 10, 10);
      context.drawImage('../../images/ping/guonei.png', 170, 277, 10, 10);
      context.fillText('全球直采', 26, 285);
      context.fillText('太平洋保险承保', 92, 285);
      context.fillText('假一赔十', 185, 285);
      context.setFontSize(10);
      context.setFillStyle('#333333');
      context.fillText('长按识别小程序码一起拼团', 12, 330);
      context.setFontSize(9);
      context.setFillStyle('#333333');
      context.fillText('真的实惠与真的朋友一起拼!', 12, 345);
      wx.downloadFile({
        url: 'http://i4.hexun.com/2018-07-05/193365388.jpg',
        success: function(res) {
          context.save()
          context.beginPath()
          context.arc(185, 340, 30, 0, 2 * Math.PI)
          context.clip()
          context.drawImage(res.tempFilePath, 155, 310, 60, 60)
          context.restore()
          context.draw(true)
        }
      })
      context.draw(true)
    },

    //文字截取
    fillTextEclip(context, text, x, y, w, fontSize, lineHeight, fontWeight, fontFamily) {
      var chr = text.split("");
      var temp = "";
      var row = [];
      context.setFontSize(fontSize)
      context.setFillStyle("#333")
      context.font = 'normal ' + fontWeight + ' ' + fontSize + 'px ' + fontFamily;
      // context.setTextAlign("left")
      for (var a = 0; a < chr.length; a++) {
        if (context.measureText(temp).width <= w) {
          temp += chr[a];
        } else {
          row.push(temp);
          temp = chr[a];
        }
      }
      row.push(temp);
      if (row.length > 2) {
        var rowCut = row.slice(0, 2);
        var rowPart = rowCut[1];
        var test = "";
        for (var a = 0; a < rowPart.length; a++) {
          if (context.measureText(test).width > (w - fontSize)) {
            break;
          }
          test += rowPart[a];
        }
        rowCut.splice(2, 1, test + "...");
        row = rowCut;
      }
      for (var b = 0; b < row.length; b++) {
        context.setFontSize(fontSize)
        context.setFillStyle("#333")
        context.font = 'normal ' + fontWeight + ' ' + fontSize + 'px ' + fontFamily;
        // context.setTextAlign("left")
        context.fillText(row[b], x, y + parseInt((lineHeight - fontSize) / 2) + b * lineHeight, w);
      }
    },

    //点击保存到相册
    saveShareImage: function() {
      var that = this;
      util.auth('scope.writePhotosAlbum', function() {
        wx.saveImageToPhotosAlbum({
          filePath: that.data.imagePath,
          success(res) {
            wx.showToast({
              title: '图片已保存到相册'
            })
            that.triggerEvent('hiddenShareDialog');
          },
          fail(res) {
            app.showToast("保存到相册失败")
          }
        })
      });
    },
    saveTempImage(drawCount, drawAll, forceDraw) {
      console.log("saveTempImage", drawCount, drawAll, forceDraw);
      let that = this;
      if (drawCount == drawAll || forceDraw) {
        setTimeout(() => {
          wx.canvasToTempFilePath({
            canvasId: 'mycanvas',
            success: function(res) {
              var tempFilePath = res.tempFilePath;
              that.setData({
                imagePath: tempFilePath
              });
              wx.hideLoading();
            },
            fail: function(res) {
              console.log("生成海报失败", res);
              wx.showToast({
                title: '生成海报失败',
                icon: "none"
              })
              wx.hideLoading();
              that.setData({
                showShareImage: false
              });
            }
          }, that);
        }, 600)
      }
    },
    //圆角
    roundRect(ctx, x, y, w, h, r) {
      ctx.beginPath()
      ctx.setStrokeStyle('#ffffff')
      ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
      ctx.moveTo(x + r, y)
      ctx.lineTo(x + w - r, y)
      ctx.lineTo(x + w, y + r)
      ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
      ctx.lineTo(x + w, y + h - r)
      ctx.lineTo(x + w - r, y + h)
      ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
      ctx.lineTo(x + r, y + h)
      ctx.lineTo(x, y + h - r)
      ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
      ctx.lineTo(x, y + r)
      ctx.lineTo(x + r, y)
      ctx.stroke()
      ctx.closePath()
      ctx.clip()
    },

    /**
     * 多行文字处理，每行显示数量
     * @param text 为传入的文本
     * @param num  为单行显示的字节长度
     */
    textByteLength(text, num) {
      let strLength = 0; // text byte length
      let rows = 1;
      let str = 0;
      let arr = [];
      for (let j = 0; j < text.length; j++) {
        if (text.charCodeAt(j) > 255) {
          strLength += 2;
          if (strLength > rows * num) {
            strLength++;
            arr.push(text.slice(str, j));
            str = j;
            rows++;
          }
        } else {
          strLength++;
          if (strLength > rows * num) {
            arr.push(text.slice(str, j));
            str = j;
            rows++;
          }
        }
      }
      arr.push(text.slice(str, text.length));
      return [strLength, arr, rows] //  [处理文字的总字节长度，每行显示内容的数组，行数]
    },
    hiddenModels: function() {
      this.triggerEvent('hiddenModels')
    },
    showMaterialModal: function() {
      this.setData({
        showMaterialModal: !this.data.showMaterialModal,
        maskShowModel: !this.data.maskShowModel
      })
    }
  }
})